package com.chang.order.web;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.chang.order.service.OrderService;
import com.chang.order.vo.PayVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author: changzhenxi
 * @date: 2025年03月26日 14:21
 * @Version: 1.0
 * @description:
 */
@Slf4j
@Controller
public class PayWebController {

    @Resource
    AlipayClient alipayClient;

    @Resource
    OrderService orderService;

    @Value("${alipay.notify-url}")
    private String notifyUrl;

    @Value("${alipay.return-url}")
    private String returnUrl;




    @ResponseBody
    @GetMapping("payOrder")
    public String payOrder(@RequestParam("orderSn") String orderSn) throws AlipayApiException {

        AlipayTradePagePayRequest payRequest = new AlipayTradePagePayRequest();
        payRequest.setReturnUrl(returnUrl);
        payRequest.setNotifyUrl(notifyUrl);

        PayVo payVo = orderService.getPayByOrderSn(orderSn);

        // 业务参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderSn); // 唯一订单号
        bizContent.put("total_amount", payVo.getTotal_amount()); // 金额
        bizContent.put("subject", payVo.getSubject()); // 订单标题
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); // PC网页支付

        payRequest.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse alipayResponse = alipayClient.pageExecute(payRequest);
        log.info(alipayResponse.getBody().toString());

        return alipayResponse.getBody(); // 返回自动提交表单的HTML
    }
}
